﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

using System.IO;
using System.Diagnostics;

using Obsolete.VoIP.Getafisk.DLL_01BL_02netfx20.any_any_any;
using Properties = Obsolete.VoIP.Getafisk.DLL_01BL_02netfx20.any_any_any.Properties;

namespace Obsolete.VoIP.Getafisk.DLL_01PL_02netfx20.WF.any_any_any
{
	public partial class UserControlMACAddresses : UserControl
	{
		# region    Variables
		//-------------------------------------------------------------------------
		string[] rows;

		string content = "";

		string template_dhcpd_host =
		@"
host leasename
{
	hardware ethernet 00:00:00:00:00:00;
	fixed-address		192.168.11.101;
}		";

		string comment = "#";
		string ip_start = "0.0.0.0";
		string network = "0.0.0.0";
		List<string> errors;
		//-------------------------------------------------------------------------
		# endregion Variables	

		public UserControlMACAddresses()
		{
			InitializeComponent();

			textBoxFile.Text = Properties.Settings.Default.DirProjectOutput;
			textBoxIPStart.Text = Properties.Settings.Default.IPAddressStart;
			textBoxIPAddressCount.Text = Properties.Settings.Default.IPAddressCount;

			listBox1.DataSource = files_provisioning;

			return;
		}


		BindingList<string> files_provisioning;

		private void GenerateProvisioningFiles()
		{
			string dir_templates_cisco;
			dir_templates_cisco = Properties.Settings.Default.DirTemplatesCisco;
			string file_template;

			Dictionary<string, string> mapping_model_template = new Dictionary<string, string>();
			errors = new List<string>();

			string template_filename;
			template_filename = dir_templates_cisco + @"7941_SEP000000000000.cnf.xml";
			mapping_model_template.Add("Cisco_7941", DataRead(template_filename));
			template_filename = dir_templates_cisco + @"7970_SEP000000000000.cnf.xml";
			mapping_model_template.Add("Cisco_7970", DataRead(template_filename));

			Dictionary<string, string> replacements = new Dictionary<string, string>();
			replacements.Add("$IP_PBX", "10.10.20.7");
			replacements.Add("$PHONE_LABEL", "");

			files_provisioning = new BindingList<string>();
			string file_provisioning = "";
			foreach (string s in rows)
			{
				if (s.StartsWith(comment))
				{
					// TODO: parse description parse comment if 1st line to extract Data
				}
				else if (s == "")
				{
					continue;
				}
				else
				{
					string[] row_parts = s.Split(new string[] { "," }, StringSplitOptions.None);

					string mac = row_parts[0];
					string type = row_parts[1].Replace(" ", "_");
					string sip_user_aka_extension = row_parts[2];
					string inbound_route = row_parts[3];
					string display_name = row_parts[4];
					string sip_password = row_parts[5];

					file_provisioning = "SEP" + mac.Replace(":","").ToUpper() + ".cnf.xml";

					string content = "";
					switch (type)
					{
						case "Cisco_7941":
							content = mapping_model_template["Cisco_7941"];
							content = content.Replace("$IP_PBX", "10.10.20.7");
							content = content.Replace("$PHONE_LABEL", inbound_route);
							content = content.Replace("$FEATURE_LABEL", sip_user_aka_extension);
							content = content.Replace("$EXTENSION", sip_user_aka_extension);
							content = content.Replace("$DISPLAY_NAME", display_name);
							content = content.Replace("$AUTH_NAME", sip_user_aka_extension);
							content = content.Replace("$AUTH_PWD",sip_password);
							content = content.Replace("$CONTACT_EXT", sip_user_aka_extension);
							DataWrite(file_provisioning, content);
							break;
						case "Cisco_7970":
							content = mapping_model_template["Cisco_7970"];
							content = content.Replace("$IP_PBX", "10.10.20.7");
							content = content.Replace("$PHONE_LABEL", inbound_route);
							content = content.Replace("$FEATURE_LABEL", sip_user_aka_extension);
							content = content.Replace("$EXTENSION", sip_user_aka_extension);
							content = content.Replace("$DISPLAY_NAME", display_name);
							content = content.Replace("$AUTH_NAME", sip_user_aka_extension);
							content = content.Replace("$AUTH_PWD",sip_password);
							content = content.Replace("$CONTACT_EXT", sip_user_aka_extension);
							DataWrite(file_provisioning, content);
							break;
						default:
							/*
							string msg = "Error! Wrong Type" + Environment.NewLine;
							msg += "mac = " + mac + Environment.NewLine;
							msg += "type = " + type + Environment.NewLine;
							msg += "sip_user_aka_extension = " + mac + Environment.NewLine;
							MessageBox.Show(msg);
							*/
							errors.Add(s);
							break;
					}
				}
				files_provisioning.Add(file_provisioning);
			}

			listBox1.DataSource = null;
			listBox1.DataSource = files_provisioning;

			textBoxErrors.Lines = errors.ToArray();

			return;
		}

		private void GenerateDHCP()
		{
			string dhcp_text = "";
			dhcp_text += "# automagically generated by HolisticWare gurus on" + DateTime.Now;
			dhcp_text += Environment.NewLine;
			dhcp_text += Environment.NewLine;
			dhcp_text += Environment.NewLine;
			dhcp_text += Environment.NewLine;

			ip_start = ParseNetworkAndIPAddress(textBoxIPStart.Text);
			int ip_start_numerical = Int32.Parse(ip_start);

			int counter = 1;
			foreach (string s in rows)
			{
				if (s.StartsWith(comment))
				{
					// TODO: parse description parse comment if 1st line to extract Data
				}
				else if (s == "")
				{
					continue;
				}
				else
				{
					string[] row_parts = s.Split(new string[] { "," }, StringSplitOptions.None);
					string mac = row_parts[0];
					string type = row_parts[1].Replace(" ", "_");
					string extension = row_parts[2];
					string ip = network + "." + (ip_start_numerical + counter).ToString();

					string host_block = "";
					host_block = template_dhcpd_host.Replace("192.168.11.101", ip);
					string leasename = "leasename_" + ip.Replace(".", "_") + "_" + type;
					host_block = host_block.Replace("leasename", leasename);
					host_block = host_block.Replace("00:00:00:00:00:00", mac);

					dhcp_text += host_block;
					counter++;
				}

			}

			textBoxIPAddressCount.Text = counter.ToString();
			textBoxDHCP.Text = dhcp_text;

			return;
		}

		private string ParseNetworkAndIPAddress(string ip_textual)
		{
			//-----------------------------------------------------------------------------------
			//  parsing network and IP address start
			int idx_last_dot = textBoxIPStart.Text.LastIndexOf(".");
			network = ip_textual.Substring(0, idx_last_dot);
			ip_start = ip_textual.Substring
									(
										idx_last_dot + 1
									, ip_textual.Length - idx_last_dot - 1
									);
			//-----------------------------------------------------------------------------------
			return ip_start;
		}


		private 
			void 
			ParseMACS
			(
				// TODO: ivan mora ovo napraviti
			)
		{
			rows = content.Split(new string[]{Environment.NewLine}, StringSplitOptions.None);

			return;
		}


		private void buttonSave_Click(object sender, EventArgs e)
		{
			// Create new SaveFileDialog object
			SaveFileDialog DialogSave = new SaveFileDialog();

			// Default file sip_user_aka_extension
			DialogSave.DefaultExt = "txt";

			// Available file extensions
			DialogSave.Filter = "Text file (*.txt)|*.txt|XML file (*.xml)|*.xml|All files (*.*)|*.*";

			// Adds a sip_user_aka_extension if the user does not
			DialogSave.AddExtension = true;

			// Restores the selected directory, next time
			DialogSave.RestoreDirectory = true;

			// Dialog title
			DialogSave.Title = "Where do you want to save the file?";

			// Startup directory
			DialogSave.InitialDirectory = textBoxFile.Text;

			string filename = "dhcpd_client_devices_voip.conf";
			// Show the dialog and process the result
			if (DialogSave.ShowDialog() == DialogResult.OK)
			{
				filename = DialogSave.FileName;
				// MessageBox.Show("You selected the file: " + filename);

				DataWrite(filename, textBoxDHCP.Text);

				DataView(filename);
			}
			else
			{
				// MessageBox.Show("You hit cancel or closed the dialog.");
			}

			DialogSave.Dispose();
			DialogSave = null;

			return;
		}

		private static void DataView(string filename)
		{
			System.Diagnostics.Process p = new System.Diagnostics.Process();
			p.StartInfo.FileName = "notepad.exe";
			p.StartInfo.Arguments = filename;
			p.Start();
			// System.Diagnostics.Process.Start("notepad.exe ");

			return;
		}

		private void DataWrite(string filename, string content)
		{
			// create a writer and open the file
			TextWriter tw = new StreamWriter(filename);

			// write a line of text to the file
			tw.Write(content);

			// close the stream
			tw.Close();
		}

		private string DataRead(string filename)
		{
			// create reader & open file
			TextReader tr = new StreamReader(filename);
			content = tr.ReadToEnd();
			// close the stream
			tr.Close();

			return content;
		}

		private void buttonRecalculate_Click(object sender, EventArgs e)
		{

			return;
		}

		private void buttonLoad_Click(object sender, EventArgs e)
		{	
			OpenFileDialog fDialog = new OpenFileDialog();
			fDialog.Title = "TXT file with MACS addresses";
			fDialog.Filter = "Text|*.txt|CSV|*.csv";
			fDialog.InitialDirectory = textBoxFile.Text;

			string filename = "";
			if (fDialog.ShowDialog() == DialogResult.OK)
			{
				filename = fDialog.FileName.ToString();
				// MessageBox.Show(filename);


				content = DataRead(filename);

				textBoxCSV.Text = content;

			}

			textBoxIPStart_TextChanged(this, null);

			return;

		}

		private void textBoxIPStart_TextChanged(object sender, EventArgs e)
		{
			ParseMACS();
			GenerateDHCP();
			GenerateProvisioningFiles();

			return;
		}

		private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
		{
			// Get the currently selected item in the ListBox.
			string curItem = listBox1.SelectedItem.ToString();

			if (curItem == String.Empty)
			{
				return;
			}
			else
			{
				string filename = 
					Properties.Settings.Default.DirProjectOutput
					+
					curItem
					;
				DataView(filename);
			}


			return;
		}

		private void button1_Click(object sender, EventArgs e)
		{
			Core.DLL_03BL_02netfx20.any_any_any.OperatingSystems.Shell.Cmd();

			Core.DLL_03BL_02netfx20.any_any_any.OperatingSystems.Shell.Bash();
			return;
		}
	}
}
